﻿using RimWorld;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using Verse;
using Verse.AI;

namespace SZ.Mech
{
    public class CompProperties_AutoJumpAbility : CompProperties_AbilityEffect
    {
        public CompProperties_AutoJumpAbility()
        {
            compClass = typeof(AutoJumpComp);
        }
    }


    public class AutoJumpComp : CompAbilityEffect
    {
        float timer;

        public override void CompTick()
        {
            if (this.parent.pawn.Spawned && !this.parent.pawn.Downed)
            {
                if (this.parent.CanCast && !this.parent.Casting)
                {
                    Pawn pawn = this.parent.pawn;
                    if (!pawn.IsColonyMechPlayerControlled)
                    {
                        timer++;
                        if (timer >= SZ_DefOf.SZJump.cooldownTicksRange.min)
                        {
                            timer = 0;
                            if (pawn.jobs.curDriver is JobDriver_AttackMelee)
                            {
                                return;
                            }
                            var melee = pawn.mindState.meleeThreat;
                            if (melee != null)
                            {
                                float distance = pawn.Position.DistanceTo(melee.Position);
                                if (distance < 3)
                                {
                                    return;
                                }
                            }

                            TargetScanFlags targetScanFlags = TargetScanFlags.NeedLOSToPawns | TargetScanFlags.NeedReachableIfCantHitFromMyPos | TargetScanFlags.NeedThreat | TargetScanFlags.NeedAutoTargetable;
                            var target = AttackTargetFinder.BestAttackTarget(pawn, targetScanFlags, null, 3, 30);
                            if (target != null)
                            {
                                var jump = this.parent.verb as Verb_CastAbilityJump;
                                JumpUtility.DoJump(pawn, target.Thing, null, jump.verbProps);
                                jump.ability.Activate(target.Thing, target.Thing);
                            }
                        }
                    }
                }
            }
            base.CompTick();
        }

        public override void PostExposeData()
        {
            base.PostExposeData();
            Scribe_Values.Look(ref timer, "timer");
        }

        public bool CanJump(Pawn pawn, LocalTargetInfo targetPosition)
        {
            float distance = pawn.Position.DistanceTo(targetPosition.Cell);
            if (distance < 30 && distance > 3)
            {
                return true;
            }
            return false;
        }

    }
}
